from datetime import datetime
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from django.utils import simplejson
import re

register = template.Library()

@register.filter
@stringfilter
def wordbreak (string, arg):
    search = '([^ ]{' + arg + '})'
    t = datetime.now()
    wbr = t.strftime("%A%d%B%Y%f") + 'wbr_here' + t.strftime("%A%d%B%Y%f")
    saferesult = conditional_escape(re.sub(search, '\\1' + wbr, string))
    result = saferesult.replace(wbr, '&shy;')
    return mark_safe(result)

@register.filter
def mult(value, arg):
  "Multiplies the arg and the value"
  return int(value) * int(arg)

@register.filter
def sub(value, arg):
    "Subtracts the arg from the value"
    return int(value) - int(arg)

@register.filter
def divminusone(value, arg):
    "Divides the value by the arg"
    return int(value - 1) / int(arg)

@register.filter
def mod(value, arg):
    return value % arg

@register.filter
def getMetadata(target, key):
  return target.getMetadata(key)

@register.filter
def getAllMetadata(target):
  result = {}
  for metadata in target.playmetadata_set.all():
    result[metadata.data_key] = metadata.data_value
  return result

@register.filter
def getGamePlaysWithType(game, type):
  return game.play_set.filter(play_type__in=type.split(',')).all()

@register.filter
def splitString(strInput, delimiter):
  return strInput.split(delimiter)

@register.filter
def getOrderedActiveGamePlayersWithPlayerAtZero(game, player_id):
  return game.getOrderedActiveGamePlayersWithPlayerAtZero(player_id)

@register.filter
def mapAccess(map, key):
  return map[key]

@register.filter
def toJson(data):
  return simplejson.dumps(data)
